from dbusSessionBus import DBusSessionBus
import session
import logging
import json
import dbus
from conf import Config
import subprocess, sys, os
from ignoreList import IgnoreList

class API():
    
    def connect(self, udpSocket, addr):
        if IgnoreList().checkIP(addr[0]) != True:
            ID = session.Session().generateID()
            session.Session().createSession(ID, addr[0])
            if Config.authMethod == 'qrcode' and DBusSessionBus.sendCommandToGUI('running'):
                subprocess.call(['qrencode', '-o', Config.qrImg, '-s', str(1), ID])
                DBusSessionBus.sendCommandToGUI('changeImage', args=[str(Config.qrImg), addr[0]])
                data = {}
                data.update({'sessionID':''})
                udpSocket.sendMessage(data, addr, False)
            else:
                data = {}
                data.update({'sessionID':ID})
                udpSocket.sendMessage(data, addr, False)
        else:
            logging.debug('IP ' + addr[0] + ' is in ignore list.')
            

    def disconnect(self, udpSocket, addr):
        session.Session().deleteSession(addr[0])
    
    def getHostName(self, udpSocket, addr):
        data = {}
        data.update({'hostname':str(udpSocket.hostname)})
        udpSocket.sendMessage(data, addr, False)
        
    def isSessionActive(self, udpSocket, addr):
        data = {}
        data.update({'active':'true'})
        udpSocket.sendMessage(str(data), addr, True)
        
#    def getList(self, parent):
#        import dbus
#        list = []
#        bus = dbus.SessionBus()
#        names = bus.list_names()
#        for i in names:
#            if str(i).rfind('mpris') != -1:
#                list.append(str(i))
#        data = {}
#        data.update({'interfaces':list})
#        parent.sock.sendto(bytes(str(data), 'utf-8'), parent.addr)
#        logging.debug('Sent response: ' + str(data) + ' to ' + parent.addr[0] + ':' + str(parent.addr[1]))

    def getList(self, udpSocket, addr):
        list = []
        bus = DBusSessionBus.bus
        names = bus.list_names()
        for i in names:
            list.append(str(i))
        data = {}
        data.update({'interfaces':list})
        udpSocket.sendMessage(data, addr, True)
        DBusSessionBus.sendCommandToGUI('removeImage')

    def ls(self, parent, path='/home/arns/test', hidden=False, relative=True):
        dirs = []
        files = []
        for nm in os.listdir(path):
            if not hidden and nm.startswith('.'):
                continue
            if not relative:
                nm = os.path.join(path, nm)
            if os.path.isdir(path+'/'+nm):
                nm = nm + '/'
                dirs.append(nm)
            elif os.path.isfile(path+'/'+nm):
                files.append(nm)
        dirs.sort()
        files.sort()
        data = str(dirs+files)[2:-2].replace("', '"," ")
        parent.sock.sendto(bytes(str(data), 'utf-8'), parent.addr)
        logging.debug('Sent response: ' + data + ' to ' + parent.addr[0] + ':' + str(parent.addr[1]))
    
    def execute(self, udpSocket, addr, string=None, commandArguments=None):
        array = string.split()
        app = array[0]
        path = array[1]
        interface = array[2]
        action = array[3]
        bus = DBusSessionBus.bus
        obj = bus.get_object(app, path)
        DBusInterface = dbus.Interface(obj, interface)
        logging.debug('Execution code: ' + string + ' . Arguments: ' + str(commandArguments))
        if action == "Notify":
            if commandArguments[2] == "":
                    commandArguments[2] = os.getcwd() + "/finger.gif"
        response = None
        try:
            try:
                response = getattr(DBusInterface, action)(*commandArguments)
            except Exception as msg:
                response = getattr(DBusInterface, action)(self)
        except Exception as msg:
            logging.error('Something went wrong... Error Code: ' + str(msg))
        
        if interface == "org.freedesktop.DBus.Properties":
            if type(response) is dbus.Dictionary:
                for i in response:
                    print(i)
                response = json.dumps(response)
            if response is not None:
                response = str(response)
                resp = {}
                resp.update({commandArguments[1]:response})
                response = str(resp)
        if response is not None:
            response = str(response)
            udpSocket.sendMessage(response, addr, True)